package com.threeti.mecool.web.controller;

import com.threeti.mecool.core.application.SearchService;
import com.threeti.mecool.core.application.acl.EmployeeService;
import com.threeti.mecool.core.application.acl.UserService;
import com.threeti.mecool.core.application.message.MessageService;
import com.threeti.mecool.core.application.plan.PlanService;
import com.threeti.mecool.core.application.project.ProjectService;
import com.threeti.mecool.core.domain.model.Communication;
import com.threeti.mecool.core.domain.model.Memo;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.domain.model.message.MobileMessage;
import com.threeti.mecool.core.domain.model.plan.PlanJobResult;
import com.threeti.mecool.core.domain.model.plan.PlanResult;
import com.threeti.mecool.core.domain.model.plan.UserStepResult;
import com.threeti.mecool.core.domain.model.plan.pojo.Plan;
import com.threeti.mecool.core.domain.model.plan.pojo.PlanJob;
import com.threeti.mecool.core.domain.model.plan.pojo.PlanProject;
import com.threeti.mecool.core.exception.MessageException;
import com.threeti.mecool.core.infrastructure.persistence.CommunicationRepository;
import com.threeti.mecool.core.infrastructure.persistence.MemoRepository;
import com.threeti.mecool.core.infrastructure.persistence.acl.UserRepository;
import com.threeti.mecool.core.infrastructure.persistence.plan.*;
import com.threeti.mecool.core.infrastructure.persistence.project.ProjectCategoryRepository;
import com.threeti.mecool.framework.util.PageHandler;
import com.threeti.mecool.web.assembler.PlanAssembler;
import com.threeti.mecool.web.form.CommunicationForm;
import com.threeti.mecool.web.form.MemoForm;
import com.threeti.mecool.web.util.RequestUtil;
import com.threeti.mecool.web.util.WebResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.data.jpa.domain.Specifications.where;

/**
 * <p/>
 * zhaoxu @ 2012-06-07 13:47
 * <p/>
 */
@Controller
@RequestMapping("/plan")
public class PlanController {
    public static final Logger logger = LoggerFactory.getLogger(PlanController.class);

    //<editor-fold desc="fields">
    @Autowired
    private MemoRepository memoRepo;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepo;

    @Autowired
    private CommunicationRepository commRepo;

    @Autowired
    private ProjectCategoryRepository projCatRepo;

    @Autowired
    private MessageService messageService;

    @Autowired
    private PlanRepository planRepository;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private PlanJobResultRepository planJobResultRepository;

    @Autowired
    private PlanResultRepository planResultRepository;

    @Autowired
    private PlanService planService;
    //</editor-fold>

    @Autowired
    private SearchService searchService;

    @Autowired
    private EmployeeService empService;

    @Autowired
    private ProjectService projectService;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/memoListData.html")
    String findByUserIdOrderByChannelCode(MemoForm memoForm, Pageable pageable, Map modelMap) {
        try {
            User user = userService.getUserFromSession();
            Page<Memo> memos = memoRepo.findAll(PlanAssembler.toCriteria(user, memoForm), pageable);
            PageHandler p = new PageHandler(pageable.getPageNumber(), Long.valueOf(memos.getTotalElements()).intValue(), pageable.getPageSize(),
                    memos.getContent());
            modelMap.put("page", p);
            return "/plan/memoListData";
        } catch (Exception e) {
            logger.error("获取备忘记录异常", e);
            return null;
        }
    }

    @RequestMapping(value = "/newMemo.html")
    public String newMemo(MemoForm memoForm) {
        Memo memo = PlanAssembler.toDom(memoForm, userService);

        try {
            memoRepo.saveAndFlush(memo);

        } catch (Exception e) {
            logger.error("新增备忘异常", e);
            return "redirect:/plan/newMemoForm.html";
        }

        return "redirect:/plan/memoList.html";
    }

    @RequestMapping(value = "/removeMemo.html")
    public String removeMemo(@RequestParam(required = true) Long memoId) {
        try {
            memoRepo.delete(memoId);
        } catch (Exception e) {
            logger.error("删除备忘异常", e);
        }

        return "redirect:/plan/memoList.html";
    }

    @RequestMapping(value = "/subordinateCommunicationList.html")
    public void subordinateCommunicationList(Map<String, Object> modelMap) {
        User user = userRepo.findWithPermissionRoleAndEntries(userService.getUserFromSession().getLoginName());
        List<User> userList = userRepo.findByLoginNameIn(planService.advancedSubordinateIdentitiesOfUser(user, true), new Sort(Sort.Direction.ASC, "displayName"));
        Iterator<User> userIterator = userList.iterator();
        Long userId = user.getId();
        while (userIterator.hasNext()) {
            if (userId.equals(userIterator.next().getId())) {
                userIterator.remove();
            }
        }
        modelMap.put("executors", userList);
    }

    @RequestMapping(value = "/subordinateCommunicationListData.html")
    public void subordinateCommunicationListData(Pageable pageable, Map<String, Object> modelMap, HttpServletRequest request) {
        try {
            if (pageable.getSort() == null) {
                pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), Sort.Direction.DESC, "recordDate");
            }
            User user = userService.getCurrentUserWithPermissionRoleAndEntries();
            List<String> userLoginNameList = planService.advancedSubordinateIdentitiesOfUser(user, true);
            modelMap.put("userLoginNames", userLoginNameList);
            modelMap.putAll(RequestUtil.getParameterMap(request));
            Page<Communication> comms = commRepo.findAll(PlanAssembler.buildSubordinateCommunicationSpecs(modelMap), pageable);
            PageHandler p = new PageHandler(pageable.getPageNumber(), Long.valueOf(comms.getTotalElements()).intValue(), pageable.getPageSize(), comms.getContent());
            modelMap.put("page", p);
        } catch (Exception e) {
            logger.error("获取下属沟通记录异常", e);
        }
    }

    @RequestMapping(value = "/subordinateCommunicationDetail/{commId}.html")
    public String subordinateCommunicationDetail(@PathVariable Long commId, Map<String, Object> modelMap) {
        modelMap.put("comm", commRepo.findOne(commId));
        return "/plan/subordinateCommunicationDetail";
    }

    @RequestMapping(value = "/communicationList.html")
    public void communicationList(CommunicationForm commForm) {
        commForm.setProjCategories(projCatRepo.findAll());
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/communicationListData.html")
    public String communicationListData(Pageable pageable, Map modelMap) {
        try {
            if (pageable.getSort() == null)
                pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), Sort.Direction.DESC, "recordDate");
            Page<Communication> comms = commRepo.findAll(pageable);
            PageHandler p = new PageHandler(pageable.getPageNumber(), Long.valueOf(comms.getTotalElements()).intValue(),
                    pageable.getPageSize(), comms.getContent());
            modelMap.put("page", p);
            return "/plan/communicationListData";
        } catch (Exception e) {
            logger.error("获取沟通记录异常", e);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/communicationDetail/{commId}.html")
    public String communicationDetail(@PathVariable Long commId, Map modelMap) {
        modelMap.put("comm", commRepo.findOne(commId));
        return "/plan/communicationDetail";
    }

    @RequestMapping(value = "/removeCommunication/{commId}.html")
    public String removeCommunication(@PathVariable Long commId) {

        try {
            commRepo.delete(commId);
        } catch (Exception e) {
            logger.error("删除沟通记录异常", e);
        }

        return "redirect:/plan/communicationList.html";
    }

    @RequestMapping("/save.html")
    @ResponseBody
    public Map<String, Object> save(@RequestBody Plan plan) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            plan.save();
            retMap.put("ok", 1);
            retMap.put("id", plan.getId());
        } catch (Exception e) {
            logger.error("save plan", e);
            retMap.put("err", e);
        }
        return retMap;
    }

    @RequestMapping("/find/{plan_id}.html")
    @ResponseBody
    public Plan find(@PathVariable("plan_id") Long planId) {
        return Plan.findById(planId);
    }

    @RequestMapping("/remove/{plan_id}.html")
    @ResponseBody
    public Map<String, Object> remove(@PathVariable("plan_id") Long planId) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            Plan plan = Plan.findById(planId);
            if (plan != null) {
                plan.delete();
            }
            retMap.put("ok", 1);
        } catch (Exception e) {
            logger.error("remove plan", e);
            retMap.put("err", e);
        }
        return retMap;
    }

    @RequestMapping("/search.html")
    @ResponseBody
    public List<Plan> search(Pageable pageable,
                             @RequestParam(value = "status", required = false) String planStatus,
                             @RequestParam(value = "name", required = false) String planName,
                             @RequestParam(value = "planDate", required = false)
                             @DateTimeFormat(pattern = "yyyy-MM-dd") Date planDate) {
        Specifications<Plan> specs = null;
        specs = buildPlanSpecs(specs, planStatus, PlanSpecs.statusIs(planStatus));
        specs = buildPlanSpecs(specs, planName, PlanSpecs.nameLike(planName));
        specs = buildPlanSpecs(specs, planDate, PlanSpecs.planDateIs(planDate));
        Page<Plan> plans = Plan.findBySpec(specs, pageable);
        return plans.getContent();
    }

    private Specifications<Plan> buildPlanSpecs(Specifications<Plan> specs, Object value, Specification<Plan> spec) {
        if (value == null || value.toString().isEmpty()) {
            return specs;
        }
        if (specs == null) {
            specs = where(spec);
        } else {
            specs = specs.and(spec);
        }
        return specs;
    }

    @RequestMapping("/test/send.html")
    @ResponseBody
    public String testSendMessage() {
        MobileMessage msg = new MobileMessage("head", "body", "test_user", "system");
        try {
            messageService.send(msg);
        } catch (MessageException e) {
            return "error: " + e.getMessage();
        }
        return "ok";
    }

    @ResponseBody
    @RequestMapping(value = "/newPlanProject.html")
    public Object newPlanProject(@RequestBody Plan plan, Map modelMap) {
        try {
            List<PlanProject> projects = plan.getPlanProjects();
            for (int i = 0; i < projects.size(); i++) {
                PlanProject planProject = projects.get(i);
                List<PlanJob> jobs = planProject.getPlanJobs();
                for (int j = 0; j < jobs.size(); j++) {
                    PlanJob planJob = jobs.get(j);
                    planJob.setJob(jobRepository.findOne(planJob.getJobId()));
                    jobs.set(j, planJob);
                }
            }

            if (plan.getUserLoginName() == null) {
                plan.setUserLoginName(userService.getUserFromSession().getLoginName());
            }

            plan.setStatus(Plan.STATUS_NEW);
            if (plan.getId() != null) {
                Plan existedPlan = Plan.findById(plan.getId());
                if (existedPlan != null) {
                    PlanResult planResult = planResultRepository.findByPlan_Id(existedPlan.getId());
                    if (planResult != null) {
                        planResultRepository.delete(planResult);
                    }
                    existedPlan.delete();
                }
            } else {
                for (PlanProject planProject : plan.getPlanProjects()) {
                    for (PlanJob planJob : planProject.getPlanJobs()) {
                        try {
                            Plan assignPlan = Plan.optAssignedPlanBy(planJob.getCooperateUser(),
                                    planProject.getProjectCode(),
                                    planJob.getStoreCode(),
                                    planJob.getJobId(),
                                    plan.getPlanDate(),
                                    planJob.getStartTime(),
                                    planJob.getEndTime());

                            String logiName = userService.getUserFromSession().getLoginName();

                            assignPlan.setAssignedBy(logiName);
                            assignPlan.setConfirmedBy(logiName);

                            assignPlan.setStatus(Plan.STATUS_CONFIRM);

                            assignPlan.save();
                        } catch (Exception e) {
                            logger.error("", e);
                        }
                    }
                }
            }

            plan.clearPersistStatus();
            plan.save();
//			planRepository.save(plan);

            WebResponse a = WebResponse.newInstance();
            a.buildModelMapData(modelMap);
            return a;
        } catch (Exception e) {
            Plan existedPlan = planRepository.findByUserLoginNameAndPlanDateAndTypeIsNull(plan.getUserLoginName(), plan.getPlanDate());
            if (existedPlan != null) {
                WebResponse a = WebResponse.newInstance();
                a.setExceptionMsg(new RuntimeException("该日期已有计划"));
                a.buildModelMapData(modelMap);
                return a;
            }
            logger.error("", e);
//			WebResponse.newInstance().
//			setExceptionMsg(e).buildModelMapData(modelMap);

            WebResponse a = WebResponse.newInstance();
            a.setExceptionMsg(e);
            a.buildModelMapData(modelMap);
            return a;
        }

    }

    @RequestMapping(value = "/planList.html")
    public void planList(Map modelMap,
                         @RequestParam(required = false) String from,
                         @RequestParam(required = false) String status) {
        modelMap.put("projCatList", projCatRepo.findAll());
        modelMap.put("users", userRepo.findAll(new Sort(Sort.Direction.ASC, "displayName")));
        modelMap.put("from", from);
        modelMap.put("status", status);
        if ("subordinate".equals(from)) {
            modelMap.put("isSubordinate", 1);
            User user = userRepo.findWithPermissionRoleAndEntries(userService.getUserFromSession().getLoginName());
            List<User> userList = userRepo.findByLoginNameIn(planService.advancedSubordinateIdentitiesOfUser(user, true), new Sort(Sort.Direction.ASC, "displayName"));
            Iterator<User> userIterator = userList.iterator();
            Long userId = user.getId();
            while (userIterator.hasNext()) {
                if (userId.equals(userIterator.next())) {
                    userIterator.remove();
                }
            }
            modelMap.put("executors", userList);
        }
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/planListData.html")
    public void planList(Map modelMap,
                         HttpServletRequest request,
                         String status,
                         Pageable pageable,
                         @RequestParam(required = false) String searchType) {

        try {
            pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), Sort.Direction.DESC, "planDate");
            User user = userRepo.findWithPermissionRoleAndEntries(userService.getUserFromSession().getLoginName());
            Page<Plan> plans;
            PageHandler p;
            Map<String, String> args = RequestUtil.getParameterMap(request);
            if ("subordinate".equals(searchType)) {
                plans = planService.findSubordinatePlansOfUser(user, args, status, pageable);

                p = new PageHandler(pageable.getPageNumber(),
                        Long.valueOf(plans.getTotalElements()).intValue(),
                        pageable.getPageSize(), plans.getContent());
            } else {
                /**
                 if(StringUtils.hasText(status)){
                 plans=planRepository.findByUserLoginNameAndStatus(user.getLoginName(),pageable,status);
                 }else{
                 plans=planRepository.findByUserLoginName(user.getLoginName(),pageable);
                 }
                 **/

                /**
                 Page<PlanJob> page = searchService.findMyPlans(args, pageable);
                 **/
                args.put("userLoginName", user.getLoginName());
                Page<Plan> page = planRepository.findAll(toPlanSpecs(args), pageable);

                p = new PageHandler(pageable.getPageNumber(),
                        Long.valueOf(page.getTotalElements()).intValue(),
                        pageable.getPageSize(),
                        page.getContent());
            }

            modelMap.put("page", p);
            modelMap.put("searchType", searchType);
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @RequestMapping(value = "/taskList.html")
    public void taskList(Map modelMap,
                         @RequestParam(value = "from", required = false) String from,
                         @RequestParam(value = "jobStatus", required = false) String jobStatus) {
        modelMap.put("projCatList", projCatRepo.findAll());
        modelMap.put("from", from);
        modelMap.put("jobStatus", jobStatus);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/taskListData.html")
    public void taskList(Map modelMap,
                         Pageable pageable,
                         @RequestParam(required = false) String searchType,
                         HttpServletRequest request) {
        User user = userRepo.findWithPermissionRoleAndEntries(userService.getUserFromSession().getLoginName());
        Map<String, String> args = RequestUtil.getParameterMap(request);
        try {
            PageHandler p;
            Page<PlanJobResult> planJobs;
            pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), Sort.Direction.DESC, "plan_date");
            if ("subordinate".equals(searchType)) {
                List<String> userLoginNameList = planService.advancedSubordinateIdentitiesOfUser(user, true);
                Iterator<String> self = userLoginNameList.iterator();
                String userLoginName = user.getLoginName();
                while (self.hasNext()) {
                    if (userLoginName.equals(self.next())) {
                        self.remove();
                    }
                }
                if (userLoginNameList.isEmpty()) {
                    p = new PageHandler(pageable.getPageNumber(), 0, pageable.getPageSize(), new ArrayList<PlanJobResult>(0));
                } else {
                        StringBuilder sb = new StringBuilder(256);
                        Iterator<String> iterator = userLoginNameList.iterator();
                        sb.append("'").append(iterator.next()).append("'");
                        while (iterator.hasNext()) {
                            sb.append(",'").append(iterator.next()).append("'");
                        }
                        args.put("userLoginNameList", sb.toString());
                    if (!user.getPermissionRole().isAdvanced()) {
//                        List<Project> projectList = projectService.findByUserOwn(user);
//                        sb = new StringBuilder(256);
//                        Iterator<Project> projectIterator = projectList.iterator();
//                        if (projectIterator.hasNext()) {
//                            sb.append("'").append(projectIterator.next().getCode()).append("'");
//                        }
//                        while (projectIterator.hasNext()) {
//                            sb.append(",'").append(projectIterator.next().getCode()).append("'");
//                        }
//                        args.put("projectCodeList", sb.toString());
                        args.put("projectCodeList", projectService.getUserInvolvedProjectCodeString(user.getEmployee().getEmpId().toString()));
                    }
                    Page<PlanJobResult> planJobResults = searchService.findJobResults(args, pageable);
                    p = new PageHandler(pageable.getPageNumber(),
                            Long.valueOf(planJobResults.getTotalElements()).intValue(),
                            pageable.getPageSize(), planJobResults.getContent());
                }
            } else {
                args.put("userLoginName", user.getLoginName());
                Page<PlanJobResult> planJobResults = searchService.findJobResults(args, pageable);
                p = new PageHandler(pageable.getPageNumber(),
                        Long.valueOf(planJobResults.getTotalElements()).intValue(),
                        pageable.getPageSize(), planJobResults.getContent());
            }
            modelMap.put("page", p);
            modelMap.put("jobStatus", args.get("jobStatus"));
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/planDetail.html")
    public void planDetail(Map modelMap, Long planId) {
        try {
            Plan plan = planRepository.findOne(planId);
            modelMap.put("plan", plan);

            if ("subordinate".equals(modelMap.get("searchType"))) {
                modelMap.put("user", userService.loadUserByUsername(plan.getUserLoginName()).getUser());
            } else {
                modelMap.put("user", userService.getUserFromSession());
            }

        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/planEdit.html")
    public void planEdit(Map modelMap,
                         Long planId,
                         @RequestParam(required = false) String searchType
    ) {

        modelMap.put("searchType", searchType);
        planDetail(modelMap, planId);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/planJobResultDetail.html")
    public void planJobResultDetail(Map modelMap, Long planJobResultId) {
        try {
            PlanJobResult planJobResult = planJobResultRepository.findOne(planJobResultId);


            List<UserStepResult> stepResults = planJobResult.getUserStepResults();


            UserStepResult[] stepResultsSorted=new UserStepResult[stepResults.size()];

            int k=0;
            for (UserStepResult userStepResult : stepResults) {
            	stepResultsSorted[k++]=userStepResult;
			}
//            for (int i = 0; i < stepResultsSorted.length; i++) {
//				for (int j = i; j < stepResultsSorted.length-1; j++) {
//					int o1=stepResultsSorted[j].getId().intValue();
//					int o2=stepResultsSorted[j+1].getStep().getId().intValue();
//					if(o1>o2){
//						UserStepResult temp=stepResultsSorted[j];
//						stepResultsSorted[j]=stepResultsSorted[j+1];
//						stepResultsSorted[j+1]=temp;
//					}
//				}
//			}

            modelMap.put("userStepResults", stepResultsSorted);
            modelMap.put("planJobResult", planJobResult);

        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @RequestMapping(value = "/planStatusEdit.html")
    public String planStatusEdit(Map modelMap,
                                 Long planId,
                                 String status,
                                 Integer planVersion,
                                 @RequestParam(required = false) String denyNotes) {
        try {
            Plan plan = planRepository.findOne(planId);
            if (!planVersion.equals(plan.getVersion())) {
                throw new RuntimeException("任务已改变，请重新刷新");
            }
            if (Plan.STATUS_DENY.equals(status)) {
                plan.setStatus(Plan.STATUS_DENY);
                plan.setDenyNotes(denyNotes);
            } else if (Plan.STATUS_CONFIRM.equals(status)) {
                plan.setStatus(Plan.STATUS_CONFIRM);
            }
            plan.setConfirmedBy(userService.getUserFromSession().getLoginName());
            plan.save();
            WebResponse.newInstance().buildModelMapData(modelMap);
        } catch (Exception e) {
            logger.error("", e);
            WebResponse.newInstance().setExceptionMsg(e).buildModelMapData(modelMap);
        }
        return WebResponse.GLOBAL_SUBMIT_CALLBACK_PAGE;
    }

    @RequestMapping(value = "/findByUserIdAndChannelCodeOrderByRecordDate.html")
    @ResponseBody
    public Object findByUserIdAndChannelCodeOrderByRecordDate(Map modelMap, String channelCode) {
        return memoRepo.findByUserIdAndChannelCodeOrderByRecordDate(userService.getUserFromSession().getLoginName(), channelCode);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/planStatus.html")
    public String planStatus(Map modelMap, Long planId) {
        try {
            Plan plan = planRepository.findOne(planId);
            modelMap.put("plan", plan);
            modelMap.put("statusEdit", "true");
        } catch (Exception e) {
            logger.error("", e);
        }

        return "plan/planDetail";
    }

    @RequestMapping("/myPlans.html")
    @ResponseBody
    public Page<PlanJob> findMyPlans(
//                                     Principal principal,
            @RequestParam("userLoginName") String userLoginName,
            Pageable pageable,
            @RequestParam(value = "planName", required = false) String planName,
            @RequestParam(value = "assignedBy", required = false) String assignedBy,
            @RequestParam(value = "planType", required = false) String planType,
            @RequestParam(value = "projectCategoryName", required = false) String projectCategoryName,
            @RequestParam(value = "planDate", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date planDate,
            @RequestParam(value = "projectName", required = false) String projectName,
            @RequestParam(value = "storeName", required = false) String storeName,
            @RequestParam(value = "planStatus", required = false) String planStatus) {
//        return searchService.findMyPlans(principal.getName(), planName, assignedBy, planType, projectCategoryName,
//                planDate, projectName, storeName, planStatus, pageable);
//        return searchService.findMyPlans(userLoginName, planName, assignedBy, planType, projectCategoryName,
//                planDate, projectName, storeName, planStatus, pageable);
        Map<String, String> args = new HashMap<String, String>();
        return searchService.findMyPlans(args, pageable);
    }

    private Specification<Plan> toPlanSpecs(Map<String, String> map) {
        Specifications<Plan> specs = null;
        String userLoginName = map.get("userLoginName");
        String planName = map.get("planName");
        String assignedBy = map.get("assignedBy");
        String confirmedBy = map.get("confirmedBy");
        String planType = map.get("planType");
        String planStatus = map.get("planStatus");
        String planDateString = map.get("planDate");
        Date planDate;
        try {
            planDate = new SimpleDateFormat("yyyy-MM-dd").parse(planDateString);
        } catch (Exception e) {
            planDate = null;
        }
        specs = buildPlanSpecs(specs, userLoginName, PlanSpecs.userLoginNameIs(userLoginName));
        specs = buildPlanSpecs(specs, planName, PlanSpecs.nameLike(planName));
        specs = buildPlanSpecs(specs, assignedBy, PlanSpecs.assignedByIs(assignedBy));
        specs = buildPlanSpecs(specs, confirmedBy, PlanSpecs.confirmedByIs(confirmedBy));
        if ("1".equals(planType)) {
            specs = specs.and(PlanSpecs.typeIsNull());
        } else if ("2".equals(planType)) {
            specs = specs.and(PlanSpecs.typeIs(Plan.TYPE_ASSIGNMENT));
        }
        specs = buildPlanSpecs(specs, planStatus, PlanSpecs.statusIs(planStatus));
        specs = buildPlanSpecs(specs, planDate, PlanSpecs.planDateIs(planDate));
        return specs;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @RequestMapping(value = "/newPlanForm.html")
    public void newPlanForm(Map modelMap) {
        User user = userService.getUserFromSession();
        modelMap.put("user", user);
        List<String[]> list = empService.getProjectCodeLoginNameDisplayName_subOf(user.getEmployee().getEmpId().toString());
        Map<String, List<Map<String, String>>> employeeMap = new HashMap<String, List<Map<String, String>>>();
        for (String[] val : list) {
            String projectCode = val[0];
            String loginName = val[1];
            String displayName = val[2];
            List<Map<String, String>> userList = employeeMap.get(projectCode);
            if (userList == null) {
                userList = new LinkedList<Map<String, String>>();
                employeeMap.put(projectCode, userList);
            }
            Map<String, String> userMap = new HashMap<String, String>();
            userMap.put("loginName", loginName);
            userMap.put("displayName", displayName);
            userList.add(userMap);
        }
//        List<ProjectEmployee> emps = empService.findSubordinateEmployeesOfUser(user);
//        for (ProjectEmployee projectEmployee : emps) {
//            Project project = projectEmployee.getProject();
//            String projectCode = project.getCode();
//            if (!employeeMap.containsKey(projectCode)) {
//                employeeMap.put(projectCode, new ArrayList());
//            }
//            User employeeUser = userRepo.findByEmployeeEmpId(projectEmployee.getEmpId());
//            if (employeeUser == null) {
//                continue;
//            }
//            Map userMap = new HashMap();
//            userMap.put("loginName", employeeUser.getLoginName());
//            userMap.put("displayName", employeeUser.getDisplayName());
//            employeeMap.get(projectCode).add(userMap);
//        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            modelMap.put("employeeMap", mapper.writeValueAsString(employeeMap));
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    private static class _ProjectEmployee {
        String projectCode, loginName, displayName;

        _ProjectEmployee(String projectCode, String loginName, String displayName) {
            this.projectCode = projectCode;
            this.loginName = loginName;
            this.displayName = displayName;
        }
    }
}
